import { ADULT } from '@/store/config.js'

//数据库是否打开
const isOpen = function (name) {
	return plus.sqlite.isOpenDatabase({
		name: name,
		path: '_doc/' + name + '.db'
	});
}
//打开数据库
const open = function ({name, success, fail}) {
	if ( !isOpen(name) ) {
		plus.sqlite.openDatabase({
			name: name,
			path: '_doc/' + name + '.db',
			success: success,
			fail: fail
		});
	} else {
		fail && fail('database ' + name + ' is opening')
	}
}
//关闭数数据库
const close = function ({name, success, fail}) {
	if ( isOpen(name) ) {
		plus.sqlite.closeDatabase({
			name: name,
			success: success,
			fail: fail
		});
	} else {
		fail && fail('database ' + name + ' is not open')
	}
}
//执行增删改sql
const executeSql = function ({name, sql, success, fail}) {
	if ( isOpen(name) ) {
		plus.sqlite.executeSql({
			name: name,
			sql: sql,
			success: success,
			fail: fail
		});
	} else {
		fail && fail('database ' + name + ' is not open')
	}
}

//执行查询sql
const selectSql = function ({name, sql, success, fail}) {
	if ( isOpen(name) ) {
		plus.sqlite.selectSql({
			name: name,
			sql: sql,
			success: function (list) {
				const arr = []
				const isAdult = uni.getStorageSync(ADULT) || 0//是否开启青壮年模式
				list.forEach(item => {
					const itemIsAdult = item.is_adult || 0//数据是否敏感
					if ( isAdult || !itemIsAdult ) {//非敏感数据或者开启青壮年模式才能输出
						const newItem = {}
						Object.keys(item).forEach(key => {
							newItem[dth(key)] = item[key]
						})
						arr.push(newItem)
					}
				})
				success && success(arr)
			},
			fail: fail
		});
	} else {
		fail && fail('database ' + name + ' is not open')
	}
}

//下横线转驼峰法
const dth = function (name) {
	return name.replace(/_(\w)/g, function (all, letter) { return letter.toUpperCase(); })
}


module.exports = {
	isOpen,
	open,
	close,
	executeSql,
	selectSql
}